# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     compress_pdf_with_pil                  |
|Author:        WYT                      |
|date:          2020/6/9                  |
 ----------------------------------------
|  Change Activity:                      |
|                   2020/6/9:             | 
-----------------------------------------
"""
# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     compress_pdf                  |
|Author:        WYT                      |
|date:          2020/6/8                  |
 ----------------------------------------
|  Change Activity:                      |
|                   2020/6/8:             | 
-----------------------------------------
"""
import os
import sys
from collections import OrderedDict

import fitz
from PIL import ImageFile, Image


class CompressPdf():

    def __init__(self, file_path="", max_size="", web_type=""):
        self.file_path = file_path
        tu = os.path.split(file_path)
        self.save_path = tu[0]
        self.save_file = tu[1]
        self.max_size = int(max_size) * 1024 * 1024
        self.file_size = os.path.getsize(file_path)
        self.rotate = int(0)
        self.avg = 0
        if web_type == "ctp":
            self.num = 70
            self.plus = 10
            self.subtract = 30
        if web_type.isdigit():
            self.num = 100

    @property
    def get_zooms(self):
        return (self.num / 100.0, self.num / 100.0)

    def get_trans(self, num=None):
        if not num:
            return fitz.Matrix(self.num / 100.0, self.num / 100.0).preRotate(self.rotate)
        else:
            return fitz.Matrix(num / 100.0, num / 100.0).preRotate(self.rotate)

    def get_pm(self, pg, matrix, alpha=False):
        return pg.getPixmap(matrix=matrix, alpha=alpha)


    def get_Pixmap(self, pg):
        num = 300
        pm = pg.getPixmap(matrix=self.get_trans(), alpha=0)
        return {"pm": pm, "num": num}


    def compress_image(self, outfile, mb=190, quality=85, k=0.9):
        """不改变图片尺寸压缩到指定大小
        :param outfile: 压缩文件保存地址
        :param mb: 压缩目标，KB
        :param step: 每次调整的压缩比率
        :param quality: 初始压缩比率
        :return: 压缩文件地址，压缩文件大小
        """
        o_size = os.path.getsize(outfile) // 1024
        # print(o_size, mb)
        if o_size <= mb:
            return outfile

        ImageFile.LOAD_TRUNCATED_IMAGES = True
        while o_size > mb:
            im = Image.open(outfile)
            x, y = im.size
            out = im.resize((int(x * k), int(y * k)), Image.ANTIALIAS)
            try:
                out.save(outfile, quality=quality)
            except Exception as e:
                print(e)
                break
            o_size = os.path.getsize(outfile) // 1024
        return outfile

    def compress(self):
        file_size = os.path.getsize(self.file_path)
        if file_size <= self.max_size:
            return True
        old_pdf = fitz.open(filename=self.file_path)
        width, height = fitz.PaperSize("a4")

        totaling = old_pdf.pageCount

        self.avg = self.max_size / totaling

        page_dict = {pg: {"pg": old_pdf[pg]} for pg in range(totaling)}
        page_order = OrderedDict(page_dict)
        # 创建目录存放中间文件
        pdf_path = os.path.splitext(self.file_path)[0]
        if not os.path.exists(pdf_path):
            os.mkdir(pdf_path)

        # self.total_size = 0
        for k, v in page_order.items():
            pg = v.get("pg")
            pm_num_dict = self.get_Pixmap(pg=pg)
            v.update(pm_num_dict)

        ratio = self.max_size / self.file_size * 1.25
        # print(self.max_size, self.file_size)
        # print(ratio)
        new_pdf = fitz.open()
        # print(pdf_path)
        for k, v in page_order.items():
            lurl = pdf_path + "\\%s.jpg" % str(k + 1)

            v.get("pm").writePNG(lurl)

            img_size = os.path.getsize(lurl)
            compress_size = img_size * ratio
            # print(img_size, compress_size)
            self.compress_image(outfile=lurl, mb=compress_size / 1024, quality=75, k=0.9)
            # print(os.path.getsize(lurl))
            # print("")

            imgdoc = fitz.open(lurl)  # 打开图片
            pdfbytes = imgdoc.convertToPDF()  # 使用图片创建单页的 PDF
            imgpdf = fitz.open("pdf", pdfbytes)
            new_pdf.insertPDF(imgpdf)  # 将当前页插入文档

        old_pdf.close()
        if os.path.exists(self.file_path):  # 若文件存在先删除
            os.remove(self.file_path)
        new_pdf.save(self.file_path, deflate=1)  # 保存pdf文件

        li = os.listdir(pdf_path)
        for i in li:
            os.remove(os.path.join(pdf_path, i))
        os.rmdir(pdf_path)
        new_pdf.close()


if __name__ == '__main__':
    CompressPdf(file_path=r"C:\Users\Administrator\Desktop\Project\autoflow\compressless\GR_2020\ctp\GR_307566\hr.pdf", max_size="2", web_type="ctp").compress()